﻿using AutoMapper;
using DotNetCore.CAP;
using IMES.Common.Domain.KeepModel.ProductionFile;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using Mysqlx.Crud;
using System.Text.Json;

namespace Keep.API.Appliction.ProductionPlanFile
{
	/// <summary>
	/// 生产计划创建
	/// </summary>
	public class ProductionPlanCreateHandler : IRequestHandler<ProductionPlanCreateCommon, Result>
	{
		private readonly IBaseRepositorys<ProductionPlan> _productionPlanReq;//生产计划
		private readonly IBaseRepositorys<PlanProductDetails> _planProductDetailsReq;//生产计划详情
		private readonly IMapper _mapper;  
		private readonly ICapPublisher _capBus; // 引入消息总线
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="productionPlanReq"></param>
		/// <param name="planProductDetailsReq"></param>
		/// <param name="mapper"></param>
		public ProductionPlanCreateHandler(IBaseRepositorys<ProductionPlan> productionPlanReq, IBaseRepositorys<PlanProductDetails> planProductDetailsReq, IMapper mapper,  ICapPublisher capBus)
		{
			_productionPlanReq = productionPlanReq;
			_planProductDetailsReq = planProductDetailsReq;
			_mapper = mapper; 
            _capBus = capBus;
		}
		/// <summary>
		/// 生产计划创建
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public Task<Result> Handle(ProductionPlanCreateCommon request, CancellationToken cancellationToken)
		{
			var result = new Result() { Code = (int)CodeEnum.success, Messege = "生产计划创建成功" };
			try
			{
				var productionPlan = _mapper.Map<ProductionPlan>(request.ProductionPlans);
                productionPlan.DocumentNumber = GetMaxProcessRouteNumber();
				var n =   _productionPlanReq.Add(productionPlan);
				if(n==0)
				{
                    result.Code = (int)CodeEnum.add;
                    result.Messege = "创建生产计划失败";
                    return Task.FromResult(result);
				}
				var num = 0;
				foreach (var item in request.PlanProductDetails)
				{
					num++;
					item.DocumentNumber = productionPlan.DocumentNumber;
					item.OrderNo  = productionPlan.DocumentNumber + "-" + num;
				}
			   var m =	_planProductDetailsReq.AddRange(request.PlanProductDetails);
				if(m == null)
				{
					result.Code = (int)CodeEnum.add;
					result.Messege = "创建生产计划失败";
					return Task.FromResult(result);
				}

				//发布消息  

				#region 
				var productionPlanReq = _productionPlanReq.GetAll().FirstOrDefault(c => c.DocumentNumber == productionPlan.DocumentNumber);//获取订单数据
				var planProductDetailsReq = _planProductDetailsReq.GetAll().Where(c => c.DocumentNumber == productionPlanReq.DocumentNumber);

				var list = new List<WorkDataDto>();
				foreach (var item in planProductDetailsReq)
				{
					var OrderShopDto = new WorkDataDto()
					{
						WorkSheetNumber = item.OrderNo,
						ProductNumber = item.ProductNumber,
						Numberofpackages = item.Quantity,//计划数
						ScheduledStartTime = new DateTime(2024, 1, 1, 8, 0, 0),
						ScheduledEndTime = new DateTime(2024, 1, 1, 17, 0, 0),
						StartTime = null,
						EndTime = null,
						State = WorkSheetState.未开始, // 替换为实际枚举值
						Remark = productionPlanReq.Remarks,
						TaskIds = "1,2",
						ProductRelatedDocuments = productionPlan.DocumentNumber,
					};
					//追加到集合中
					list.Add(OrderShopDto);
				}
				//发布消息
				string PublishInformation = JsonSerializer.Serialize(list);
				// 添加消息头
				IDictionary<string, string> dicHeader = new Dictionary<string, string>(); 
				dicHeader.Add(key: "One", value: PublishInformation);
				// 发布消息
				_capBus.Publish(name: "RabbitMQ.Production-WorkSheet", contentObj: productionPlanReq, headers: dicHeader);
				#endregion
			}
			catch (Exception ex)
			{
				result.Code = (int)CodeEnum.error;
				result.Messege = ex.Message;
			}
			return Task.FromResult(result);
		}
		/// <summary>
		/// 获取最大流程编号
		/// </summary>
		/// <returns></returns>
		private string GetMaxProcessRouteNumber()
		{
			var list = _planProductDetailsReq.GetAll().Max(a => a.PlanProductDetailsId);
			if (list == 0)
			{
				return GenerateId(1);
			}
			return GenerateId(list + 1);
		}
		/// <summary>
		/// 前缀
		/// </summary>
		private static readonly string prefix = "SCJH";
		/// <summary>
		/// 生成流程编号
		/// </summary>
		/// <param name="counter"></param>
		/// <returns></returns>
		public static string GenerateId(int counter)
		{
			string datetimeStr = DateTime.Now.ToString("yyyyMMddHHmmss");
			string sequenceStr = counter.ToString("D5");
			string result = prefix + datetimeStr + "-" + sequenceStr;
			return result;
		}
	}
}
